获取布局android中动态添加视图的位置值

时间:2016-04-29 09:18:33

标签: java android view

我正在尝试本教程:http://android-er.blogspot.in/2014/01/get-text-from-dynamically-added-view.html \ 当用户单击插入按钮时我试图编辑文本,只有当我将位置作为静态值时它才能正常工作。 但当我试图获得位置时,这个应用程序不幸停止了。

public class MainActivity extends Activity {
 EditText textIn;
 Button buttonAdd;
 LinearLayout container;
 Button buttonShowAll;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textIn = (EditText)findViewById(R.id.textin);
  buttonAdd = (Button)findViewById(R.id.add);
  container = (LinearLayout)findViewById(R.id.container);

  buttonAdd.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    LayoutInflater layoutInflater = 
      (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View addView = layoutInflater.inflate(R.layout.row, null);
    final TextView textOut = (TextView)addView.findViewById(R.id.textout);
    textOut.setText(textIn.getText().toString());
    Button buttonRemove = (Button)addView.findViewById(R.id.remove);
    buttonRemove.setOnClickListener(new OnClickListener(){

     @Override
     public void onClick(View v) {
      ((LinearLayout)addView.getParent()).removeView(addView);
     }});

    Button buttonInsert = (Button)addView.findViewById(R.id.insert);
    buttonInsert.setOnClickListener(new OnClickListener(){

     @Override
     public void onClick(View v) {
                        //int position = (Integer)v.getTag();   // I m trying to get position of button here but stops the app
                        int position = 2; // Static value for changing the textview works fine
                        String showallPrompt = "";
                        View childView = container.getChildAt(position);
                        TextView childTextView = (TextView) (childView.findViewById(R.id.textout));
                        String childTextViewText = (String) (childTextView.getText());
                        showallPrompt += position + ": " + childTextViewText + "\n";
                        Toast.makeText(MainActivity.this,
                                showallPrompt,
                                Toast.LENGTH_LONG).show();
                        ((TextView) (childTextView.findViewById(R.id.textout))).setText("HELLO ");
     }});

    container.addView(addView, 0);
   }});

  LayoutTransition transition = new LayoutTransition();
  container.setLayoutTransition(transition);
  }
}

所以在这里,我曾经通过

获得职位
//int position = (Integer)v.getTag();   // I m trying to get position of button here but stops the app
    int position = 2; // Static value for changing the textview works fine

但没有工作。如何解决这个问题。实际上我想用可编辑的文本做listview并显示为textview。

0 个答案:

没有答案