Check this image sample i have done it Material Design Gridview Image
I have done the same Material Design for grid view Activity on my app, i like to add the onItemClick to new Activity,
I don't know how to do this , please give the brief explanation for the solution
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:id="#+id/appbar_layout"
android:layout_height="#dimen/app_bar_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_android_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="#dimen/expanded_toolbar_title_margin_start"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerInside"
android:src="#drawable/code"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:id="#+id/nestedscrollview"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<GridView
android:id="#+id/grid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:gravity="center"
android:listSelector="#00000000"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
res/layout/gridview_custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/android_gridview_custom_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp">
<com.andexert.library.RippleView
android:id="#+id/more"
rv_centered="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:rv_color="#fff"
app:rv_rippleDuration="200">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:orientation="vertical">
<ImageView
android:id="#+id/gridview_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/gridview_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/grid_image"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Grid View Item"
android:textColor="#444"
android:textSize="12sp"
android:textStyle="bold" />
</LinearLayout>
</com.andexert.library.RippleView>
</LinearLayout>
src/MainActivity.java
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.GridView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
src/CustomAndroidGridViewAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by HP on 5/11/2016.
*/
public class CustomAndroidGridViewAdapter extends BaseAdapter {
private Context mContext;
private final String[] string;
private final int[] Imageid;
public CustomAndroidGridViewAdapter(Context c,String[] string,int[] Imageid ) {
mContext = c;
this.Imageid = Imageid;
this.string = string;
}
#Override
public int getCount() {
return string.length;
}
#Override
public Object getItem(int p) {
return null;
}
#Override
public long getItemId(int p) {
return 0;
}
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
} else {
grid = (View) convertView;
}
return grid;
}
}
PLease give me the solution for call another Actvivty when mouse click on Image (Image 1, Image 2, etc) in Gridview this
Replace your method with mine
#Override
public View getView(int p, View convertView, ViewGroup parent) {
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.gridview_custom_layout, null);
TextView textView = (TextView) grid.findViewById(R.id.gridview_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.gridview_image);
textView.setText(string[p]);
imageView.setImageResource(Imageid[p]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,YourActivity.class);
context.startActivity(intent);
}
});
} else {
grid = (View) convertView;
}
return grid;
}
here is the code to go another activity after click on every image.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
CollapsingToolbarLayout collapsingToolbarLayoutAndroid;
CoordinatorLayout rootLayoutAndroid;
GridView gridView;
Context context;
ArrayList arrayList;
public static String[] gridViewStrings = {
"Android",
"Java",
"GridView",
"ListView",
"Adapter",
"Custom GridView",
"Material",
"XML",
"Code",
};
public static int[] gridViewImages = {
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic,
R.drawable.android_ic
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(1))){
Intent intent=new Intent(MainActivity.this,SecoundActivity.class);
intent.putExtra("image",gridViewImages[position]);
startActivity(intent);
}
else if(gridViewStrings[position].equalsIgnoreCase(String.valueOf(2))){
Intent intent2=new Intent(MainActivity.this,ThirdActvity.class);
intent2.putExtra("image2",gridViewImages[position]);
startActivity(intent2);
}
//Like this create activites how many images are there in gridViewImages[]array.you have 9 images so create nine activities..you have to send the url in every activity from one activity to another activity according to your requirement
}
});
gridView.setAdapter(new CustomAndroidGridViewAdapter(this, gridViewStrings, gridViewImages));
initInstances();
}
private void initInstances() {
rootLayoutAndroid = (CoordinatorLayout) findViewById(R.id.android_coordinator_layout);
collapsingToolbarLayoutAndroid = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_android_layout);
collapsingToolbarLayoutAndroid.setTitle("Material Grid");
}
}
create SecoundActivity.class
public class SecoundActivity extends AppCompactActivity{
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent=getIntent();
int position = intent.getExtras().getInt("image");
setContentView(R.layout.secound_view);
image=(ImageView) findViewById(R.id.image);
image.setImageResource(position);
}
}
then Finally create the secound_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_horizontal_margin">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/image"
/>
</LinearLayout>
After 10 seconds in Google...
Starting Another Activity
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);
And Click Listener/Event
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Item Clicked: " + position, Toast.LENGTH_SHORT).show();
}
});
In your MainActivity onCreate method, add an OnItemClick listener for the GridView:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Your Intent goes here
}
});
Related
I am trying to create a horizontal slider of images fitted in my imageview in my main layout file. But instead of imageview sliding on touch, the code is moving the whole layout horizontally.
Following is my Java code for sliding:
public class Artprofile extends FragmentActivity {
static final int NUM_ITEMS = 5;
ImageFragmentPagerAdapter imageFragmentPagerAdapter;
ViewPager viewPager;
public static final String[] IMAGE_NAME = {"a", "b", "c", "d", "e",};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_page);
imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View swipeView = inflater.inflate(R.layout.layoutart, container, false);
ImageView imageView = (ImageView) swipeView.findViewById(R.id.image_view1);
Bundle bundle = getArguments();
int position = bundle.getInt("position");
String imageFileName = IMAGE_NAME[position];
int imgResId = getResources().getIdentifier(imageFileName, "drawable", "com.example.user.myapplication1");
imageView.setImageResource(imgResId);
return swipeView;
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
}
}
Following is my main layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/mobileback"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView android:id="#+id/image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:maxWidth="150dp"
android:maxHeight="150dp"
android:scaleType="fitCenter"
android:layout_marginRight="50dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="400dp"
android:src="#drawable/profilewindow1"
android:layout_marginEnd="58dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="330dp"
android:layout_alignParentStart="true"
android:maxWidth="150dp"
android:maxHeight="150dp"
android:layout_below="#+id/image_view"
android:id="#+id/layout_mobile1">
<ImageView
android:id="#+id/image_view1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</FrameLayout>
</RelativeLayout>
And this is the Fragment layout used for sliding:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
I dont understand the problem. Kindly help. Thanks in advance
You can use a layout to wrap imageview and then wrap the layout in horizontal scrollview
So this has been bugging me for like a week and I haven't found the answer yet.
Basically I have this MainActivity which contains the main code and a fragment that work for the listview.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler handler = new Handler();
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private Button bNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RoomServer(), "Room Server");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
RoomServer.java
public class RoomServer extends ListFragment implements OnItemClickListener{
public RoomServer() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rs, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(getListView().CHOICE_MODE_MULTIPLE);
getListView().setTextFilterEnabled(true);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.rs_list, android.R.layout.simple_list_item_checked);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
Fragment_rs.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.RoomServer">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
<Button
android:id="#+id/bNext_rs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/next"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp"
android:layout_marginBottom="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
activity_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
The items of listview r declared inside strings.XML
As u can see I'm using CHOICE_MODE_MULTIPLE to create checkbox in the listview. And now I'm stuck at how to get the value of this checkbox. I'm planning to use Volley to send value to my database by a button click. Most of the answer I saw was using the isChecked and stuff but I dont really understand how to implement it in my array adapter.
You can either implement a custom array adapter yourself, or use this method in the ListView class to get a SparseBooleanArray of the indexes of the selected items:
//Submit button example
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Get base list
String[] items = getActivity().getResources().getStringArray(R.array.rs_list);
//Get selected items & set intent args
SparseBooleanArray selectedItems = getListView().getCheckedItemPositions();
ArrayList<String> argList = new ArrayList<>();
for (int i = 0; i < selectedItems.size(); i++) {
argList.add(items[selectedItems.keyAt(i)]);
}
//Start activity
Intent intent = new Intent();
intent.putStringArrayListExtra("SelectedItems", argList);
getActivity().startActivity(intent);
}
});
I am just starting with android, so I don't have much to show of what I have so far...
I am trying to make a to-do list. I have seen tutorials on how to do this with a menu for input and have the tasks displayed in a ListView, however I would like the user to input the task into an EditText instead. I was using this (which doesn't use a ListView) to just have a button click make a new TextView underneath the EditText, however I couldn't add buttons next to the TextView which would remove it (when the user finishes a task).
Using a ListView seems much easier for this, but how can I have the EditText input go to a ListView with all the tasks and buttons to remove them (permanently, not just set visibility to 0)? I would also like the tasks to be stored, so the user can close the app and return with the tasks still there.
Any ideas? I haven't made much progress.
I recommend you to use RecyclerView instead of Listview. compile this in your Gradle
compile 'com.levelupstudio:expandable-recyclerview:1.0.1'
Here is the mainActivity.java
public class MainActivity extends ActionBarActivity implements
RecyclerViewAdapter.OnItemClickListener{
private RecyclerView myRecyclerView;
private LinearLayoutManager linearLayoutManager;
private RecyclerViewAdapter myRecyclerViewAdapter;
EditText nameField;
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myRecyclerView = (RecyclerView)findViewById(R.id.myrecyclerview);
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
/*
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
*/
myRecyclerViewAdapter = new RecyclerViewAdapter(this);
myRecyclerViewAdapter.setOnItemClickListener(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
nameField = (EditText)findViewById(R.id.namefield);
btnAdd = (Button)findViewById(R.id.addbutton);
btnAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String newName = nameField.getText().toString();
Context context= getApplicationContext();
myRecyclerViewAdapter.add(0,newName);
Toast.makeText(context,"You added" +newName.toUpperCase()+ "in your view",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onItemClick(RecyclerViewAdapter.ItemHolder item, int position) {
Toast.makeText(this,
"Remove " + position + " : " + item.getItemName(),
Toast.LENGTH_SHORT).show();
}}
And AdapterClass for Recycler
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ItemHolder> {
private List<String> itemsName;
private OnItemClickListener onItemClickListener;
private LayoutInflater layoutInflater;
public RecyclerViewAdapter(Context context){
layoutInflater = LayoutInflater.from(context);
itemsName = new ArrayList<String>();
}
#Override
public RecyclerViewAdapter.ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = layoutInflater.inflate(R.layout.list_item, parent, false);
return new ItemHolder(itemView, this);
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.ItemHolder holder, int position) {
holder.setItemName(itemsName.get(position));
}
#Override
public int getItemCount() {
return itemsName.size();
}
public void setOnItemClickListener(OnItemClickListener listener){
onItemClickListener = listener;
}
public OnItemClickListener getOnItemClickListener(){
return onItemClickListener;
}
public interface OnItemClickListener{
public void onItemClick(ItemHolder item, int position);
}
public void add(int location, String iName){
itemsName.add(location, iName);
notifyItemInserted(location);
}
public static class ItemHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private RecyclerViewAdapter parent;
TextView textItemName;
public ItemHolder(View itemView, RecyclerViewAdapter parent) {
super(itemView);
itemView.setOnClickListener(this);
this.parent = parent;
textItemName = (TextView) itemView.findViewById(R.id.item_name);
}
public void setItemName(CharSequence name){
textItemName.setText(name);
}
public CharSequence getItemName(){
return textItemName.getText();
}
#Override
public void onClick(View v) {
final OnItemClickListener listener = parent.getOnItemClickListener();
if(listener != null){
listener.onItemClick(this, getPosition());
}
}
}}
and your xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/namefield"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/addbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add"/>
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/myrecyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
list_xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="16dp"
android:background="#android:color/holo_blue_light"
android:orientation="vertical">
<TextView
android:id="#+id/item_name"
android:layout_centerVertical="true"
android:layout_margin="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
I've been searching for hours and hours on trying to understand the relationship between Fragments and Activities and I still cant get it right with my code.
I have a mainScreen class that loads actvity_main.xml. This main screen has a layout with a graph and sidebar etc.
I have a button that is on the side bar that is supposed to launch a sidebar fragment that has a checkbox listview in it so I can select data to show on my graph etc. But that fragment is not showing no matter what I do. It shows the "Bing~!" Toast but no other view is launched.
Perhaps I shouldn't be using a fragment? I don't want to start a new activity as the checkbox is supposed to interact with the graph and another fragment with a dynamic table in it and it will interact back and forth and so on.
I'm not too sure what to do here. I have about 3 weeks of Android experience so I'm not exactly knowledgeable about the whole shebang of it just yet. Really appreciate any ideas or help I can get. I am completely stumped and hence had to post my own question.
I really really appreciate any kind of help! Thanks!
mainScreen.java
public class mainScreen extends Activity {
private TextView text_display;
private Button button_list;
private Button button_table;
private String[] dataHolder;
public boolean listClicked = false;
public void loadData () {
//loaddata stuff here
}
public void createGraph () {
//graph create stuff here
}
public void buttonClick () {
button_list.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
sideFragment sf = new sideFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.side_fragment, sf);
ft.commit();
Toast.makeText(mainScreen.this, "Bing~!", Toast.LENGTH_SHORT).show();
}
}
);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = getIntent();
dataHolder = i.getStringArrayExtra("dataHolder");
button_list = (Button)findViewById(R.id.button_list);
loadData();
createGraph();
buttonClick();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".mainScreen"
android:id="#+id/mainlayout"
android:orientation="horizontal"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="85dp"
android:layout_height="match_parent">
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="85dp"
android:layout_height="85dp"
android:text="Select"
android:id="#+id/button_list" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="85dp"
android:layout_height="85dp"
android:text="Table"
android:id="#+id/button_table" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:text=" "
android:id="#+id/text_display"
android:textSize="26dp"
android:layout_margin="5dp" />
<com.jjoe64.graphview.GraphView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/graph" />
</LinearLayout>
<fragment
android:name="xabre.mobileicip.sideFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/side_fragment" />
</LinearLayout>
sideFragment.java
public class sideFragment extends Fragment implements android.widget.CompoundButton.OnCheckedChangeListener {
ListView listviewFrag;
ArrayList<sideFrag> sideFragList;
sideFragAdapter sfAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.side_fragment, container, false);
listviewFrag = (ListView) view.findViewById(R.id.side_listview);
//displayList();
return view;
}
private void displayList() {
sideFragList = new ArrayList<sideFrag>();
sideFragList.add(new sideFrag("SPO2"));
sideFragList.add(new sideFrag("O2 Flow Rate"));
sideFragList.add(new sideFrag("Resp."));
sideFragList.add(new sideFrag("Cardiac Output"));
sideFragList.add(new sideFrag("Cardiac Index"));
sideFragList.add(new sideFrag("SVR"));
sideFragList.add(new sideFrag("Wedge Pressure"));
listviewFrag.setAdapter(sfAdapter);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = listviewFrag.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
sideFrag sf = sideFragList.get(pos);
sf.setSelected(isChecked);
Toast.makeText(getActivity(),"" + sf.getName(), Toast.LENGTH_SHORT).show();
//Toast.makeText(sideFragment.this, "Clicked on sideFrag: " + sf.getName() + ". State: is " + isChecked, Toast.LENGTH_SHORT).show();
}
}
}
side_fragment.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".sideFragment"
android:id="#id/side_fragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="HELLO WORLD"
android:id="#+id/helloTester"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp">
<ListView
android:id="#+id/side_listview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</LinearLayout>
side_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<CheckBox android:id="#+id/check_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"
android:layout_marginBottom="15dp" />
<TextView
android:id="#+id/check_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/check_box"
android:textStyle="bold"/>
</RelativeLayout>
sideFragAdapter.java
package xabre.mobileicip;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.List;
class sideFrag {
String name;
boolean selected = false;
public sideFrag(String name) {
super();
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class sideFragAdapter extends ArrayAdapter<sideFrag> implements CompoundButton.OnCheckedChangeListener {
private List<sideFrag> sideList;
private Context context;
public sideFragAdapter (List<sideFrag> sideList, Context context) {
super(context, R.layout.side_list, sideList);
this.sideList = sideList;
this.context = context;
}
private static class sideHolder {
public CheckBox check_box;
public TextView check_name;
/* public CheckBox check_O2FR;
public CheckBox check_Resp;
public CheckBox check_Carout;
public CheckBox check_Carind;
public CheckBox check_svr;
public CheckBox check_resprate;
public CheckBox check_Peep;
public CheckBox check_O2AF;
public CheckBox check_FIO2;
public CheckBox check_PO2;
public CheckBox check_HCO3;
public CheckBox check_Urea;
public CheckBox check_Potassium;
public CheckBox check_Sodium;
public CheckBox check_Creatinine;
public CheckBox check_FluidIn;
public CheckBox check_FluidOut;
*/
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
sideHolder holder = new sideHolder();
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.side_list, parent, false);
holder.check_box = (CheckBox) v.findViewById(R.id.checkbox);
holder.check_name = (TextView) v.findViewById(R.id.check_name);
holder.check_box.setOnCheckedChangeListener(this);
} else {
holder = (sideHolder) v.getTag();
}
sideFrag p = sideList.get(position);
holder.check_name.setText(p.getName());
holder.check_box.setChecked(p.isSelected());
holder.check_box.setTag(p);
return v;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
}
}
You can only replace elements added from code. side_fragment is added in XML and as such is part of, let's say "read only" structure. You need to remove <fragment> element it from XML, and add it from code if you want to replace it later.
I want to fix a button on top of the layout and just below the button a dynamic edit text is created. I am creating my own Adapter. On button click another activity starts and returns string which is to be shown on the list view items below the button. How can I do this ?
My XML Layout -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<EditText
android:id="#+id/etList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
</LinearLayout>
My list view adapter -
package com.example.tasktable;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class TaskAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
Button click;
TextView textView;
public TaskAdapter(Context context, String[] values) {
super(context, R.layout.list_view, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflator.inflate(R.layout.list_view, parent, false);
click = (Button) rowView.findViewById(R.id.button1);
textView = (TextView) rowView.findViewById(R.id.etList);
textView.setText(values[position]);
return rowView;
}
}
I don't want to inflate button with every edit text.
You can position layout elements with Relative Layouts https://developer.android.com/reference/android/widget/RelativeLayout.html
//try this way, hope this will help you...
**XML** code
**activity.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:id="#+id/lnrEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</ScrollView>
</LinearLayout>
**list_activity.xml**
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
**list_item.xml**
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/txtValue"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btnSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select"/>
</LinearLayout>
**ACTIVITY** code
**MyActivity**
public class MyActivity extends Activity{
private Button btnAdd;
private LinearLayout lnrEdit;
private final int GET_LIST_ITEM = 1;
private HashMap<String,String> listItemMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
btnAdd = (Button) findViewById(R.id.btnAdd);
lnrEdit = (LinearLayout) findViewById(R.id.lnrEdit);
listItemMap = new HashMap<String, String>();
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this,MyListActivty.class);
startActivityForResult(intent,GET_LIST_ITEM);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == GET_LIST_ITEM);
{
String getListValue = data.getStringExtra("value");
int index = data.getIntExtra("index",0);
if(listItemMap.containsKey(String.valueOf(index))){
Toast.makeText(this,"This item already taken !!!",Toast.LENGTH_LONG).show();
} else{
listItemMap.put(String.valueOf(index),getListValue);
EditText editText = new EditText(this);
editText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setId(index);
editText.setText(getListValue);
editText.setTag(getListValue);
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
editText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = v.getTag().toString();
Toast.makeText(MyActivity.this,value,Toast.LENGTH_SHORT).show();
}
});
lnrEdit.addView(editText);
}
}
}
}
}
**MyListActivity**
public class MyListActivty extends ListActivity{
private String[] listArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
listArray = new String[]{"Android4.1","Android4.2","Android4.3","Android4.4","Android4.5"};
setListAdapter(new TaskAdapter(this,listArray));
}
class TaskAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public TaskAdapter(Context context, String[] values) {
super(context, R.layout.list_item, values);
this.context = context;
this.values = values;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
holder.button = (Button) convertView.findViewById(R.id.btnSelect);
holder.textView = (TextView) convertView.findViewById(R.id.txtValue);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(values[position]);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("index",position);
intent.putExtra("value",values[position]);
setResult(RESULT_OK,intent);
finish();
}
});
return convertView;
}
#Override
public int getCount() {
return values.length;
}
}
static class ViewHolder{
Button button;
TextView textView;
}
}