根据2个微调框加载图像

时间:2019-06-16 19:44:20

标签: android google-maps android-activity

我有两项活动:第一项是MainActivity,另一项是ShowMap。我想根据第一个活动中的微调框值在第二个活动中加载图像。

为便于说明,如果用户在两个微调器中选择两个位置,然后按下“显示地图”按钮,他/她将能够看到图像。如果用户在微调器中选择另一个值,则图像将发生变化。我该如何实现?

MainActivity.java

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner spinner1, spinner2;
ImageView img;
Button button;

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

    // first spinner (From)
    spinner1 = (Spinner) findViewById(R.id.from);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.places, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);

    // second spinner (To)

    spinner2 = (Spinner) findViewById(R.id.to);
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
            R.array.places, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(adapter1);


    String value1 = spinner1.getSelectedItem().toString();
    String value2 = spinner2.getSelectedItem().toString();





    button = (Button) findViewById(R.id.btn1);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(MainActivity.this,ShowMap.class));


        }
    });


    img = (ImageView) findViewById(R.id.pic_map);
    int image1 = R.drawable.sn;
    int image2 = R.drawable.an;


}

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

    switch (i){
        case 0:
            img.setBackgroundResource(R.drawable.ac);
            break;
        case 1:
            img.setBackgroundResource(R.drawable.as);
            break;


    }

}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}


}

ShowMap.java

public class ShowMap extends AppCompatActivity {

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


}

1 个答案:

答案 0 :(得分:0)

首先为图像创建一个值,例如:

String data="img1";

然后在您的onItemSelected中将值更改为类似img1img2的值 。最后,在您的button.setOnClickListener中开始活动,其意图如下:

String value="Hello world";
Intent i = new Intent(CurrentActivity.this, NewActivity.class);    
i.putExtra("key",data);
startActivity(i);

现在您的第二项活动:

Bundle extras = getIntent().getExtras();
if (extras != null) {
   String value = extras.getString("key");
   //The key argument here must match that used in the other activity
}

并根据该值设置图像。