我使用for
循環創建了一些ImageView
s,並將它們插入到ScrollView
中。'this'關鍵字不起作用
然後我需要在觸摸屏幕時再創建一個ImageView
。 this
關鍵字不能用於在'###'標記的位置創建ImageView
。
我是初學者。
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ScrollView scroll=new ScrollView(this);
final LinearLayout layout =new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lparams.setMargins(0, 10, 0, 10);
lparams.gravity=Gravity.CENTER;
int i;
for(i=0;i<15;i++) {
//here 'this' is working ******************
ImageView imView = new ImageView(this);
imView.setLayoutParams(lparams);
Drawable new_image = getResources().getDrawable(R.drawable.rakthasakshi);
imView.setBackgroundDrawable(new_image);
layout.addView(imView, lparams);
}
scroll.addView(layout);
setContentView(scroll);
scroll.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
//but here says 'this' cannot be applied ###############
ImageView imView = new ImageView(this);
imView.setLayoutParams(lparams);
Drawable new_image = getResources().getDrawable(R.drawable.rakthasakshi);
imView.setBackgroundDrawable(new_image);
layout.addView(imView, lparams);
scroll.addView(layout);
setContentView(scroll);
return true;
}
return false;
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
非常感謝...它的工作.. :-)我知道它的一種參考,但不知道如何處理它.. –
我很高興你學會了'這個'哈哈 – shkschneider