I'm trying to change the layout of my activity according to my selection inside the spinner.
But after the first selection, the spinner become white and I'm not able to decide another selection.
The code I'm using is the following:
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinner;
String[] options = { "Modulo1", "Modulo2" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, options);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter_state);
spinner.setOnItemSelectedListener(this);
}
int check = 0;
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
check = check + 1;
if (check > 1) {
int selState = spinner.getSelectedItemPosition();
switch (selState) {
case 0:
setContentView(R.layout.activity_main);
break;
case 1:
setContentView(R.layout.activity2_main);
break;
}
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
//
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Any suggestion?
Thanks
The spinner you are referring to is in your first activity. After you have replaced the content, the spinner isn't there anymore. If you have another spinner in the second layout, you have to reconnect it and set the listener again.
Basically you have to run your onCreate stuff after every setContentView...
As a side note, whatever you are trying to do, this is probably not the way to go. To show another full layout, better use another activity.
Related
I have this activity with some adapters , I would put it in tableLayout I already try some methods ,
unfortunately they didn't work , ( extends FragmentActivity , Convert Activity to Fragment with using onCreateView() )
`public class MainActivity_Delete extends AppCompatActivity` {
private SwipeMenuListView listView;
private ArrayList<Data> dataArrayList;
private ListAdapter listAdapter;
private Data data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete);
listView = (SwipeMenuListView) findViewById(R.id.listview);
dataArrayList = new ArrayList<>();
listAdapter = new ListAdapter(this, dataArrayList);
listView.setAdapter(listAdapter);
listView.setMenuCreator(creator);
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
switch (index) {
case 0:
Toast.makeText(MainActivity_Delete.this, "Delete", Toast.LENGTH_SHORT).show();
Log.e("item", String.valueOf(listView.getAdapter().getItem(position)));
Log.e("name", String.valueOf(dataArrayList.get(position).getName()));
dataArrayList.remove(position);
listAdapter.notifyDataSetChanged();
break;
case 1:
// delete
break;
}
// false : close the menu; true : not close the menu
return false;
}
});
}
SwipeMenuCreator creator = new SwipeMenuCreator() {
#Override
public void create(SwipeMenu menu) {
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getApplicationContext());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.parseColor("#F45557")));
// set item width
deleteItem.setWidth(150);
deleteItem.setTitle("Delete");
deleteItem.setTitleColor(Color.WHITE);
deleteItem.setTitleSize(15);
// add to menu
menu.addMenuItem(deleteItem);
}
};
}
There is android.app.ActivityGroup but this class has been deprecated since API level 13. So, in essence you cannot embed an activity in another activity. You can reuse layout files, however. See Re-using Layouts with <include/> The best option is, of course, to make use of fragments. They are the standard for such things.
I think I'm missing an important part in understanding how to call the spinner from the action bar, considering that apparently the callbacks onItemSelected and onNothingSelected apparently are not being called.
Can someone give an idea please? I've read plenty of other questions like these but didn't find the solution.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Confifure the spinner for radius selection.
setUpSpinner();
}
/**
* Set up the spinner.
* */
public void setUpSpinner(){
// Instantiate the spinner.
mSpinner = new Spinner(this);
// Create an ArrayAdapter using the string array and a default spinner layout.
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.radius_config, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears.
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(this);
}
/**
* Called when the user pressed the menu button.
* */
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* Called when the user clicks at an item on the menu.
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.radius_config:
mSpinner.performClick();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Spinner callback, when an item on the spinner is clicked.
* */
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("map values", "Position: " + position);
}
/**
* Spinner callback, when no iten is selected.
* */
#Override
public void onNothingSelected(AdapterView<?> parent) {
Log.d("map values", "Nothing");
}
I found a code from here
it is like
public class MainActivity extends ListActivity implements
SwipeActionAdapter.SwipeActionListener
{
protected SwipeActionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] content = new String[20];
for (int i=0;i<20;i++) content[i] = "Row "+(i+1);
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(
this,
R.layout.row_bg,
R.id.text,
new ArrayList<String>(Arrays.asList(content))
);
mAdapter = new SwipeActionAdapter(stringAdapter);
mAdapter.setSwipeActionListener(this)
.setListView(getListView());
setListAdapter(mAdapter);
mAdapter.addBackground(SwipeDirections.DIRECTION_FAR_LEFT,R.layout.row_bg_left_far)
.addBackground(SwipeDirections.DIRECTION_NORMAL_LEFT,R.layout.row_bg_left)
.addBackground(SwipeDirections.DIRECTION_FAR_RIGHT,R.layout.row_bg_right_far)
.addBackground(SwipeDirections.DIRECTION_NORMAL_RIGHT,R.layout.row_bg_right);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView listView, View view, int position, long id){
Toast.makeText(
this,
"Clicked "+mAdapter.getItem(position),
Toast.LENGTH_SHORT
).show();
}
#Override
public boolean hasActions(int position){
return true;
}
#Override
public boolean shouldDismiss(int position, int direction){
return direction == SwipeDirections.DIRECTION_NORMAL_LEFT;
}
#Override
public void onSwipe(int[] positionList, int[] directionList){
for(int i=0;i<positionList.length;i++) {
int direction = directionList[i];
int position = positionList[i];
String dir = "";
switch (direction) {
case SwipeDirections.DIRECTION_FAR_LEFT:
dir = "Far left";
break;
case SwipeDirections.DIRECTION_NORMAL_LEFT:
dir = "Left";
break;
case SwipeDirections.DIRECTION_FAR_RIGHT:
dir = "Far right";
break;
case SwipeDirections.DIRECTION_NORMAL_RIGHT:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Test Dialog").setMessage("You swiped right").create().show();
dir = "Right";
break;
}
Toast.makeText(
this,
dir + " swipe Action triggered on " + mAdapter.getItem(position),
Toast.LENGTH_SHORT
).show();
mAdapter.notifyDataSetChanged();
}
}
}
I want to remove the string section and want to display apps.
I want to use SwipeActionAdapter to replace listview from my app which i used earlier to show app packages but unable to understand how to do that with this..
Go a bit easy on me if this is a very noob-ish question. I m a begginer.
I think you are misunderstanding the purpose of the Adapter.
The Adapter is the component that feeds the data into your ListView.
The SwipeActionAdapter is meant to wrap around your existing implementation of Adapter and provide callbacks that you can use to perform actions when someone swipes an item in your ListView.
You should probably go through a bit more tutorials. I can greatly recommend the Busy Coders guide to Android development by Commonsware.
I'm certain you'll find what you need there.
Following the code given in the sample app here, I created an activity which can add EditTexts on the screen. I would like to know how to assign them IDs so that I can extract the text entered or already present in them.
Please help. Thanks in advance.
public class MainActivity extends ActionBarActivity {
private ViewGroup mContainerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainerView = (ViewGroup) findViewById(R.id.container);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_add_item:
// Hide the "empty" view since there is now at least one item in the list.
findViewById(android.R.id.empty).setVisibility(View.GONE);
addItem();
return true;
}
return super.onOptionsItemSelected(item);
}
private void addItem() {
// Instantiate a new "row" view.
final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
R.layout.list_item_example, mContainerView, false);
// Set the text in the new row to a random country.
((EditText) newView.findViewById(android.R.id.text1)).setText(
COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);
// Set a click listener for the "X" button in the row that will remove the row.
newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Remove the row from its parent (the container view).
// Because mContainerView has android:animateLayoutChanges set to true,
// this removal is automatically animated.
mContainerView.removeView(newView);
// If there are no rows remaining, show the empty view.
if (mContainerView.getChildCount() == 0) {
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
}
}
});
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
mContainerView.addView(newView, mContainerView.getChildCount());
}
/**
* A static list of country names.
*/
private static final String[] COUNTRIES = new String[]{
"Belgium", "France", "Italy", "Germany", "Spain",
"Austria", "Russia", "Poland", "Croatia", "Greece",
"Ukraine",
};
}
You don't assign IDs to the Views, they are generated automatically in android.R. To retrieve them use findViewById(R.resource)
final EditText edit = (EditText) findViewById(R.id.resource);
String myText = edit.getText.tostring();
I have a listview populated with data from a cursor using SimpleCursorAdapter. I want to make it so I can select multiple items with a checkbox against each item but I can only get it to check a single item at a time i.e. each time I select an item, it will clear the currently selected item.
It works fine if I populate the listview using an ArrayAdapter. I can select multiple items. So I dont know why it doesn't work with the SimpleCursorAdapter.
This is being created in a DialogFragment if that matters.
Really pulling my hair out on this, pleae help!!
Here's the code:
Cursor attributesCursor = mDBHelper.getItemAttributesbyType(menuID, itemID, "M");
getActivity().startManagingCursor(attributesCursor);
ListView lv = new ListView(this.getActivity());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
lv.setLayoutParams(params);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getActivity(), android.R.layout.simple_list_item_multiple_choice,
attributesCursor, new String[] { "AttributeDescription" },
new int[] { android.R.id.text1 },0);
attributesLinearLayout.addView(lv);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Edit :
Just to add some extra info, the multi choice listview works if i use this code, where "items" is a simple String array:
lv.setAdapter(new ArrayAdapter(this.getActivity(),
android.R.layout.simple_list_item_multiple_choice, items));
Also, this listview is being dynamically added to an existing Linearlayout (attributesLinearLayout) in a dialogfragment which contains other controls. I also tried extending other adapters, including the array adapter and customer item layouts but that again didnt allow me to select multiple items.
Please help!!
I would use the Contextual Action mode in this project if you wish to select multiple items in a listview. This is how it is done.
First of all, the code must extend a ListActivity and implement an ActionMode.Callback
In the onCreate medthod you need to code the following:
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String[] values = new String[] { "data list goes here" };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
setListAdapter(adapter);
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (mActionMode != null) {
return false;
}
selectedItem = position;
// Start the CAB using the ActionMode.Callback defined above
mActionMode = MyListActivityActionbar.this.startActionMode(MyListActivityActionbar.this);
view.setSelected(true);
return true;
}
});
}
The you need to call the show method:
private void show() {
Toast.makeText(MyListActivityActionbar.this, String.valueOf(selectedItem), Toast.LENGTH_LONG).show();
}
The following needs to be called each time the action mode is shown. It is always called after onCreateActionMode, but may be called multiple times if the mode is invalidated:
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
Then when the user selects a list item, the following method needs to be called:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1_show:
show();
// Action picked, so close the CAB
mode.finish();
return true;
default:
return false;
}
}
Finally when the user exits the selection:
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
selectedItem = -1;
}