Badrinath
Badrinath

Reputation: 355

How to Identify the linear layout from ten linearlayouts in android

I have 10 LinearLayouts how to identify the each linearlayout, so that onclick of that i need to perform some action on it

Below is the code

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.item);


    newsLayout =(LinearLayout)findViewById(R.id.newsLayout);        

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      RelativeLayout rel=null;
        for(int i=0;i<images.size();i++){
            rel= new RelativeLayout(this);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            rel.setId(i);
            rel = (RelativeLayout) inflater.inflate(R.layout.reuse,null);

            params.setMargins(0, 50, 0, 0);

             TextView fromWeb= (TextView) rel.findViewById(R.id.text);
             fromWeb.setText(headLines.get(i));
             newsLayout.addView(rel,params);



 rel.setOnClickListener(new RelativeLayout.OnClickListener() {
            public void onClick(View arg0) {   
                switch(arg0.getId())   { 

       case 1: Toast.makeText(DesignShape.this, "clicked"+arg0.getId(),           Toast.LENGTH_LONG).show();       
    break;     

 default: break; 
        }
    } 
});
    }



    }

On click event on linear layout resulting in the same object everytime. how can i distinguih from each other

Upvotes: 1

Views: 226

Answers (2)

Ben Weiss
Ben Weiss

Reputation: 17932

You can identify your layouts with a switch case like so:

public void onClick(View arg0) {
  switch(arg0.getId()):
    case R.id.layout1:
      Toast.makeText(DesignShape.this, "clicked"+arg0.getId(), Toast.LENGTH_LONG).show();
      break;
    default:
      break;
}

Further you can set implement your OnClickListener within your Activity rather than creating a new one for each view.

But since you inflate the same layout in your for loop you can not distinguish between the layouts without modification of the view's id. So calling view.setId(i) might also help.

Try using a ListView instead and implement the Adapter's OnItemClickListener.

Upvotes: 0

Akilan
Akilan

Reputation: 1717

You can give the id to the every linearlayout and write a case to getid in the layout on click.

Upvotes: 1

Related Questions