如何在android中动态膨胀按钮

时间:2016-05-10 19:30:49

标签: android button

我一直在努力让膨胀按钮起作用。这是代码:

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View editBtn = layoutInflater.inflate(R.layout.list_item, null);
Button editTaskBtn = (Button) editBtn.findViewById(R.id.editTaskbutton);
editTaskBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent1 = new Intent(v.getContext(), Activity8.class);
        startActivityForResult(intent1,0);
    }
});

关于如何让按钮工作的任何想法?

1 个答案:

答案 0 :(得分:1)

看看这个

public class InflateExActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        LinearLayout lLayout;
        final Button b = null;

        final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        for(int i=0;i<3;i++){
            View v = inflater.inflate(R.layout.buttons, null);
            b = v.findViewById(R.id.your_button_id);
            //  b = (Button) inflater.inflate(R.layout.buttons, null);
            b.setTag(i); // you'll get 0,1,2 as tags

            lLayout = (LinearLayout) findViewById(R.id.layout1);
            lLayout.addView(b);

            b.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    int specificButton = (Integer)v.getTag();//Changed here.......
                    Toast.makeText(InflateExActivity.this, 
                            "Button Clicked"+Integer.toString(specificButton),
                            Toast.LENGTH_LONG).show();
                }
            });
        }
    }  

}