Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use single xml layout for multiple activities with different datas

I know this is a very basic question, however as a newbie i cant get to work around it. So, I want to have multiple activities to use same the xml layout(consist for example of 1 imagebutton, and multiple textviews with different IDs). Now, for every activity, I want them to view the same layout but override the views with data unique to every activity. What is the best way to do this? And also, the imagebutton should open different URLs in a video player(youtube links).

And can somebody tell me what is the most practical way to learn android programming?

UPDATE This is my current code:

public class TemakiActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.contentviewer);
}

}

For example I have a textview with ID "descriptionviewer", and a button with ID "videolink", now, how do you code those in?

like image 240
borislemke Avatar asked Jan 06 '12 06:01

borislemke


2 Answers

You can share the same layout file and the set the attributes for views in the onCreate(..) method of each activity.

If you want a different URL to open for each image button you could set it at runtime as follows

public void onCreate(Bundle b) {

    Button button =(Button)findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            //different action for each activity
        }
    });
}
like image 60
Rajdeep Dua Avatar answered Oct 16 '22 07:10

Rajdeep Dua


Yes you can! I had multiple activities inflate the same layout but they save different shared preferences.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.same_layout);

    TextView urlDesc = (TextView)findViewById(R.id.descriptionviewer);
    urlDesc.setText("url_1"); //now in other activities-- urlDesc.setText("url_2");


    ImageButton aButton = (ImageButton)findViewById(R.id.videolink);
    aButton.setOnClickListener(aButtonListener);
}

private OnClickListener aButtonListener = new OnClickListener() {
    public void onClick(View v) {
        // go open url_1 here. In other activities, open url_x, url_y, url_z
        finish();
    }
};

Same code just swapping the text you want to set for the TextView and url to open in OnClickListener(). No more to change.

like image 26
Yini Avatar answered Oct 16 '22 08:10

Yini