So this is the deal, I have tried looking at other threads like this one here
https://stackoverflow.com/questions/12479909/how-to-make-list-header-and-footer-not-click-able
But it doesn't work. I can't manage to "do nothing on click".
But the problem is not to handle what hapens when the list is clicked, that is that the list is giving feedback as if its been clicked (I.E lights up), and I don't want that.
I don't understand why the part below doesn't work (I.E it is still selectable/clickable)
ViewGroup footer = (ViewGroup)inflater.inflate(R.layout.listview_footer_row, null, false);//This is not working as it should
listView.addFooterView(footer);
Anyone have any idea why my footer is clickable/selectable despite i add te false statment to the method?
Here is my code
import java.util.ArrayList;
import android.content.Intent;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
public class PortfolioFragMent extends Fragment{
private ListView listView;
private Button goButton;
private String[] listheader = {"Idag","Senaste","Antal","Avkastning %","Avkastning","Tot Värde"};
private static ShareHoldingAdapter adapter;
private int totalElemInlist = listheader.length;
private int currentelemInList=0;
private ArrayList<ShareHolding> allShareHoldings = new ArrayList<ShareHolding>();
private Button buyButton;
#SuppressLint("NewApi")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#SuppressLint({ "NewApi", "NewApi" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
allShareHoldings = Portfolio.getPortfolio().getAllShareHoldings();
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.portfolioframe, container, false);
listView = (ListView)view.findViewById(R.id.listView1);
String[] array = new String[] {"one", "two", "three"};
/**********************************/
adapter = new ShareHoldingAdapter(getActivity(), R.layout.listview_item_row, allShareHoldings);
/***********************************/
ViewGroup header = (ViewGroup)inflater.inflate(R.layout.listview_header_row, null, false);
ViewGroup footer = (ViewGroup)inflater.inflate(R.layout.listview_footer_row, null, false);//This is not working as it should
listView.addHeaderView(header);
listView.addFooterView(footer);
goButton = (Button)view.findViewById(R.id.testButton);
goButton.setText(listheader[currentelemInList]);
listView.setAdapter(adapter);
goButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
String buttonPressed = (String) ((Button) view).getText();
currentelemInList++;
if(currentelemInList>=totalElemInlist){
currentelemInList=0;
}
adapter.setButtonPressed(currentelemInList);
goButton.setText(listheader[currentelemInList]);
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
/*
* Have to catch Nullpointer exception here since I have two elements in list plus 1 header and 1 footer.
* When I click the footer I sent the number 3 to my next intent (4-1). But I don't want the footer to fire on click at all
*/
if(position<Portfolio.getPortfolio().count()){//Just to check that I havn't clicked listFooter.
System.out.println("Klicka i listan");
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailShareHoldingActivity.class);
intent.putExtra("new_variable_name","value");
intent.putExtra("bookPositionInList",(position-1));//Just so that the top of the list is not clicked
System.out.println(position);
startActivity(intent);
}
}
});
buyButton = (Button)view.findViewById(R.id.buyNewShares);
buyButton.setOnClickListener(new OnClickListener() {public void onClick(View view) {
buyShares();
}});
return view;
}
#SuppressLint({ "NewApi", "NewApi" })
private void buyShares(){
System.out.println("Köpt tryckt");
Intent intent = new Intent(getActivity().getApplicationContext(),
BuyNewSharesActivity.class);
startActivity(intent);
}
#SuppressLint({ "NewApi", "NewApi" })
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("Klicka i listan");
Intent intent = new Intent(getActivity().getApplicationContext(),
DetailShareHoldingActivity.class);
intent.putExtra("new_variable_name","value");
intent.putExtra("bookPositionInList",position);
startActivity(intent);
}
public static ShareHoldingAdapter getPortfolioFragmentShareHoldingAdapter(){
return adapter;
}
}
And here is my listview_footer_row.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableLayout
android:id="#+id/book_detailTable"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="top"
android:layout_weight="1"
android:paddingTop="0dip" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top"
android:paddingTop="0dip" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:gravity="left"
android:text="Namn"
android:textColor="#ababab"
android:textSize="25dip" />
</TableRow>
</TableLayout>
</LinearLayout>
instead of using
addFooterView(v)
use
List.addFooterView(v, data, isSelectable);
and set isselectable = false
List.addFooterView(v, null,false);
so your footerView is no longer selectable
Related
This is my code which I used to make my data fetched from my data base in form of a list.But it is refreshing at all time when scroll down after a scrolled up for an instant . I need to make the refresh avail only when it is at top.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.adapter.ConnectAdapter;
import com.shuan.Project.asyncTasks.GetHome;
import com.shuan.Project.asyncTasks.GetPost;
import com.shuan.Project.employer.PostViewActivity;
import com.shuan.Project.list.Sample;
import java.util.ArrayList;
import java.util.HashMap;
public class OffersFragment extends Fragment {
private ArrayList<Sample> list;
private ConnectAdapter adapter;
private ListView listView;
private HashMap<String, String> cData;
private Common mApp;
private Context mContext;
private ProgressBar progressBar;
private SwipeRefreshLayout swipe;
public OffersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext=getActivity();
mApp= (Common) mContext.getApplicationContext();
View view = inflater.inflate(R.layout.fragment_employer_home, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
listView = (ListView) view.findViewById(R.id.post);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
list = new ArrayList<Sample>();
new GetPost(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id,""),"all", swipe).execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
TextView txt1= (TextView) view.findViewById(R.id.frm_id);
Intent in=new Intent(getActivity(),PostViewActivity.class);
in.putExtra("jId",txt.getText().toString());
in.putExtra("frmId",txt1.getText().toString());
in.putExtra("apply","no");
startActivity(in);
}
});
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new GetHome(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id, ""), "all",swipe).execute();
}
});
return view;
}
}
my xml file
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout 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="com.shuan.Project.fragment.ConnectionFragment">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<ListView
android:id="#+id/post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:visibility="gone" />
</RelativeLayout>
Change your xml layout so SwipeRefreshLayout only wrap a scrollable view (your case the ListView).
<RelativeLayout 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="com.shuan.Project.fragment.ConnectionFragment">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/post"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#null"
android:visibility="gone" />
</android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.enhancedListView.EnhancedListView
android:id="#+id/listaNoticias"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="5dp" >
</com.enhancedListView.EnhancedListView>
</android.support.v4.widget.SwipeRefreshLayout>
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.principal, container, false);
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(android.R.color.holo_green_dark,
android.R.color.holo_red_dark,
android.R.color.holo_blue_dark,
android.R.color.holo_orange_dark); (...)
#Override
public void onRefresh() {
new myTask().execute();
}
I found my own solution for the question above. We can solve the issue by change the above code like below.
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.shuan.Project.R;
import com.shuan.Project.Utils.Common;
import com.shuan.Project.adapter.ConnectAdapter;
import com.shuan.Project.asyncTasks.GetHome;
import com.shuan.Project.asyncTasks.GetPost;
import com.shuan.Project.employer.PostViewActivity;
import com.shuan.Project.list.Sample;
import java.util.ArrayList;
import java.util.HashMap;
public class OffersFragment extends Fragment implements AbsListView.OnScrollListener {
private ArrayList<Sample> list;
private ConnectAdapter adapter;
private ListView listView;
private HashMap<String, String> cData;
private Common mApp;
private Context mContext;
private ProgressBar progressBar;
private SwipeRefreshLayout swipe;
private int preLast;
public OffersFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mContext=getActivity();
mApp= (Common) mContext.getApplicationContext();
View view = inflater.inflate(R.layout.fragment_employer_home, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe);
listView = (ListView) view.findViewById(R.id.post);
progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
list = new ArrayList<Sample>();
new GetPost(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id,""),"all", swipe).execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView txt = (TextView) view.findViewById(R.id.jId);
TextView txt1= (TextView) view.findViewById(R.id.frm_id);
Intent in=new Intent(getActivity(),PostViewActivity.class);
in.putExtra("jId",txt.getText().toString());
in.putExtra("frmId",txt1.getText().toString());
in.putExtra("apply","no");
startActivity(in);
}
});
listView.setOnScrollListener(this);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new GetHome(getActivity(), listView, progressBar, mApp.getPreference().getString(Common.u_id, ""), "all",swipe).execute();
}
});
return view;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (view.getId() == R.id.post) {
if (firstVisibleItem == 0) {
swipe.setEnabled(true);
int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount) {
if (preLast != lastItem) {
preLast = lastItem;
//Toast.makeText(getActivity(), "In Last", Toast.LENGTH_SHORT).show();
}
}else{
}
} else {
swipe.setEnabled(false);
}
}
}
}
This is a bit old, but in 2019 this is the correct answer: you have to include RecyclerView inside of NestedScrollView in order for SwipeRefreshLayout to behave properly, like this:
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipeRefreshLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
add this lines of code
note : LinearLayoutManager should be define separately
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mSwipeRefreshLayout.setEnabled
(mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
}
});
findFirstCompletelyVisibleItemPosition() == 0 means at the top of recyclerview
I am new in android
The structure of my application consist of:
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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.reyhane.myapplication.MainActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.design.widget.CoordinatorLayout>
cell.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layoutDirection="rtl">
<TableRow
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/nationalCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<TextView
android:id="#+id/lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginLeft="8dp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:text="حذف" />
</TableRow>
</TableLayout>
MainActivity.java
package com.example.reyhane.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends Activity {
public ListView list;
public ArrayList<Person> countries = new ArrayList<Person>();
public ListAdapter adapter;
public void fillPerson(String nationalCode) {
Person person = new Person();
person.setNationalCode(nationalCode);
person.setName("reza");
person.setLastName("hghgh");
person.setPhone("231345");
countries.add(person);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
fillPerson("6768767");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
adapter = new ListAdapter(this);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Object o = list.getItemAtPosition(position);
Person person = (Person) o;
openAddPersonActivity(person.getNationalCode());
}
});
}
public void openAddPersonActivity(String nationalCode) {
Intent i = new Intent(MainActivity.this, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
}
ListAdapter.java
package com.example.reyhane.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;
/**
* Created by reyhane on 11/24/16.
*/
public class ListAdapter extends BaseAdapter {
MainActivity mainActivity;
ListAdapter(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
public int getCount() {
return mainActivity.countries.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolderItem {
TextView nationalCode;
TextView name;
TextView lastName;
TextView phone;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolderItem holder = new ViewHolderItem();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cell, null);
holder.nationalCode = (TextView) convertView.findViewById(R.id.nationalCode);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.lastName = (TextView) convertView.findViewById(R.id.lastName);
convertView.setTag(holder);
} else {
holder = (ViewHolderItem) convertView.getTag();
}
Button deleteBtn = (Button) convertView.findViewById(R.id.delete_btn);
holder.nationalCode.setText(this.mainActivity.countries.get(position).getNationalCode());
holder.name.setText(this.mainActivity.countries.get(position).getName());
holder.lastName.setText(this.mainActivity.countries.get(position).getLastName());
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
mainActivity.countries.remove(position); //or some other task
notifyDataSetChanged();
}
});
return convertView;
}
}
My problem:
As you see in my application, i have list of person in listview.
In this form i add person and delete and edit it.
I can remove each record of listview but i can not get nationalCode value of person of each reacord in listview to fetch person from database by this nationalcode and edit it.
How do i do?
please help me
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3)
{
String nationalcode = (String) ((TextView) v.findViewById(R.id.nationalcode)).getText();
Toast.makeText(getApplicationContext(), "NATIONAL CODE "+nationalcode, Toast.LENGTH_SHORT).show();
openAddPersonActivity(nationalcode);
}
});
Hope it helps.
try this :
openAddPersonActivity(countries.get(position).getNationalCode());
FYI, the list.setOnItemClick doesn't work
add this into your ListAdapter:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mainActivity,"Country Code = "+MainActivity.countries.get(position).getNationalCode(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(mainActivity, AddPerson.class);
if (nationalCode != null)
i.putExtra("nationalCode", nationalCode);
startActivity(i);
}
});
and if you click country code in listview item then it will detected;
You have not set countries list to your Listview adaptor.
When you are setting the adaptor, pass the countries list to listview adaptor.
It work successfully:
holder.nationalCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String nationalcode = (String) ((TextView) view.findViewById(R.id.nationalCode)).getText();
Toast.makeText(mainActivity, "NATIONAL CODE " + nationalcode, Toast.LENGTH_SHORT).show();
}
});
Try This
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Person person = countries.get(position);
openAddPersonActivity(person.getNationalCode());
}
I've done some research but I've found myself getting quite confused on the topic of ListViews and creating a button within a ListView.
For my project, I have a ListView created in one layout.xml (called recap_page.xml) and in another layout.xml (row_layout.xml) I have the layout view (the layout on row_layout.xml is what is displayed on recap page)
The rows are populated with data entered by the user in another activity using SQLiteDatabase (DataEntryHome.java) (not relevant for this, but I'm just giving some context)
Basically, what I want to do is to have the button in each row open a new activity. As it stands, when I press the button, the app crashes. I believe I have to use a method that links to the button by using onClick. I have tried this by creating a method called viewOrder although I'm not sure which activity I have to put the method in because I've confused myself by creating different activities for different purposes.
Is anyone able to help me and explain:
a) What steps I have to take to make these buttons responsive?
b) What activities do I need to implement them into?
My code
recap_page.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list_view"
android:textColor="#000000"
android:clickable="true">
</ListView>
</RelativeLayout>
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#30609d">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/firstNameText"
android:text="First name here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/surnameText"
android:text="Surname here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="#+id/emailText"
android:text="Email here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:id="#+id/phoneText"
android:text="Phone here"
android:gravity="center"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:id="#+id/addInfoText"
android:text="Additional info"
android:gravity="center"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="53dp"
android:layout_height="37dp"
android:text="GO"
android:id="#+id/goButton"
android:onClick="viewOrder"
android:layout_marginTop="7dp"/>
</LinearLayout>
</ScrollView>
RecapPage.java
package com.example.joe.printedclothing;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class RecapPage extends AppCompatActivity{
String classNames[] = {"HomeActivity", "SelectDesign"};
ListView listView;
SQLiteDatabase sqLiteDatabase;
UserDbHelper userDbHelper;
Cursor cursor;
ListDataAdapter listDataAdapter;
Button goButtonAction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recap_page);
goButtonAction = (Button) findViewById(R.id.goButton);
listView = (ListView) findViewById(R.id.list_view);
listView.setClickable(true);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper(getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformation(sqLiteDatabase);
if(cursor.moveToFirst()) {
do {
String first_name, surname, email, phone, add_info;
first_name = cursor.getString(0);
surname = cursor.getString(1);
email = cursor.getString(2);
phone = cursor.getString(3);
add_info = cursor.getString(4);
DataProvider dataProvider = new DataProvider(first_name,surname,email,phone,add_info);
listDataAdapter.add(dataProvider);
} while (cursor.moveToNext());
}
Intent arrayItems = getIntent();
Bundle arrayItemsBundle = arrayItems.getExtras();
}
}
ListDataAdapter.java
package com.example.joe.printedclothing;
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.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ListDataAdapter extends ArrayAdapter {
List list = new ArrayList();
public ListDataAdapter(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler {
TextView FIRSTNAME, SURNAME, EMAIL, PHONE, ADDINFO;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.FIRSTNAME = (TextView) row.findViewById(R.id.firstNameText);
layoutHandler.SURNAME = (TextView) row.findViewById(R.id.surnameText);
layoutHandler.EMAIL = (TextView) row.findViewById(R.id.emailText);
layoutHandler.PHONE = (TextView) row.findViewById(R.id.phoneText);
layoutHandler.ADDINFO = (TextView) row.findViewById(R.id.addInfoText);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.FIRSTNAME.setText(dataProvider.getFirst_name());
layoutHandler.SURNAME.setText(dataProvider.getSurname());
layoutHandler.EMAIL.setText(dataProvider.getEmail());
layoutHandler.PHONE.setText(dataProvider.getPhone());
layoutHandler.ADDINFO.setText(dataProvider.getAdd_info());
return row;
}
}
And I don't know why, but here's my home activity:
package com.example.joe.printedclothing;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
public class HomeActivity extends AppCompatActivity {
private static Button StagHenButton, ReviewOrder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
StagHenButton = (Button) findViewById(R.id.StagHen); // Locates the button that the user presses to move to the next activity
StagHenButton.setOnClickListener( // When the button is clicked...create an intent to move to next activity
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent newIntent = new Intent("com.example.joe.printedclothing.SelectDesign"); // Intent to choose next activity
startActivity(newIntent);
}
}
);
}
public void addContact (View view) {
Intent intent = new Intent(this,DataEntryHome.class);
startActivity(intent);
}
public void viewContact (View view) {
Intent intent = new Intent(HomeActivity.this, RecapPage.class);
startActivity(intent);
}
public void viewOrder (View view) {
Intent intent = new Intent(HomeActivity.this, RecapPage.class);
startActivity(intent);
}
#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_home, 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);
}
}
You can set the OnClickListener in the Adapter.getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.FIRSTNAME = (TextView) row.findViewById(R.id.firstNameText);
layoutHandler.SURNAME = (TextView) row.findViewById(R.id.surnameText);
layoutHandler.EMAIL = (TextView) row.findViewById(R.id.emailText);
layoutHandler.PHONE = (TextView) row.findViewById(R.id.phoneText);
layoutHandler.ADDINFO = (TextView) row.findViewById(R.id.addInfoText);
layoutHandler.goButton = (Button) row.findViewById(R.id.goButton);
row.setTag(layoutHandler);
}
else {
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.FIRSTNAME.setText(dataProvider.getFirst_name());
layoutHandler.SURNAME.setText(dataProvider.getSurname());
layoutHandler.EMAIL.setText(dataProvider.getEmail());
layoutHandler.PHONE.setText(dataProvider.getPhone());
layoutHandler.ADDINFO.setText(dataProvider.getAdd_info());
layoutHandler.goButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
//Start your activity here
}
}
);
return row;
}
Just put the below code in your function from where you want to launch new Activity.This is the tested code.It might be helpful for you
Intent i=new Intent(getContext(),Main2Activity.class);
getContext().startActivity(i);
I am making A Chat Application on Android.
These are some of the files
I'm trying to get the String(name) that is in the ListView. When I click the name, I want it to go to a new activity ChatBox. How would I get a String that the user clicks on?
I attempted a few times in freindslist.java for method contactOnClick() I'm guessing I just have to fix that somehow to be able to function the way I want it to. Because, It seems as if the contactOnClick() isn't connected right with the ListView.
FriendsList.Java:
package com.example.swagmessenger5;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
public class FriendsList extends ListActivity {
ListView listOfContacts;
static String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friends_list);
//create string names
String[] names = {"tim", "liz" , "ori" , "john" , "bryan","tim", "liz" , "ori" , "john" , "bryan","tim", "liz" , "ori" , "john" , "bryan" };
//get online status boolean
boolean[] status = {true, false, true, false, true, true, false, true, false, true,true, false, true, false, true };
//they should be intertwined, meaning boolean lined up with string.
MyArrayAdapter adapter = new MyArrayAdapter(this, names, status );
this.setListAdapter(adapter);
}
public void contactOnClick(View view){ //go to chat box with the talker name on top
//View myLayout = findViewById( R.id.lol );
listOfContacts = (ListView) findViewById( R.id.lol ); //need to et rigt text
listOfContacts.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
data = (String)arg0.getItemAtPosition(arg2);
}});
Intent intent = new Intent(this, ChatBox.class);
startActivity(intent);
}
//** code to make arrays go forever can keep adding.
/* public static void main(String[] args) {
int[] series = {4,2};
series = addElement(series, 3);
series = addElement(series, 1);
}
static int[] addElement(int[] a, int e) {
a = Arrays.copyOf(a, a.length + 1);
a[a.length - 1] = e;
return a;
} */
public void addfriend(View view){ //go to add friend page
Intent intent = new Intent(this, AddFriend.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.friends_list, menu);
return true;
}
}
This is the layout with the include in it.
activity_friends_list.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/swag_plus"
android:onClick="addfriend" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/button1"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:text="#string/swag_list"
android:textAppearance="?android:attr/textAppearanceLarge" />
<include
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
layout="#layout/activity_box_in_list_view"
android:onClick="contactOnClick"
android:id="#+id/lol" />
</RelativeLayout>
BoxInListView.java
package com.example.swagmessenger5;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.Menu;
public class BoxInListView extends ListActivity {
//this is the friends list where it will inflate all the friends into the list veiw
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_box_in_list_view);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.box_in_list_view, menu);
return true;
}
}
This is the file where the ListView is made. And this is the file that is being included into the friendslit xml.
activity_box_in_list_view.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imageView1"
android:padding="15dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="14dp"
android:paddingTop="25dp"/>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Here is My ArrayAdapter
the array adapter is inflating in box_in_list_view
MyArrayAdapter.java
package com.example.swagmessenger5;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyArrayAdapter extends ArrayAdapter<String> {
private Context context;
private String[] names;
private boolean[] status;
public MyArrayAdapter(Context context, String[] names, boolean[] status) {
super(context, R.layout.activity_box_in_list_view, names);
this.context = context;
this.names = names; //names in array
this.status = status; //names in status
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_box_in_list_view, parent, false);
//Text view
TextView nameView = (TextView) rowView.findViewById(R.id.textView1); //set id to text view variable
ImageView onlineView = (ImageView) rowView.findViewById(R.id.imageView1); //set id to image view variable
nameView.setText(names[position]); //set textview(name) of the name in the right position
// Check the status if online or offline
boolean online = status[position];
if (online) //if online is true, the picture will be set to on
onlineView.setImageResource(android.R.drawable.button_onoff_indicator_on);
else //if online is false, the picture will be set to off
onlineView.setImageResource(android.R.drawable.button_onoff_indicator_off);
return rowView;
}
}
Set an OnClickListener for the view inside getView in the adapter. Also, you can set the name to be the tag of the rootview to make things easier. Then you can have code like this in the OnClickListener:
public void onClick(View v){
String name = (String)v.getTag();
doStuffWithName(name);
}
In my app, I have three tabs. In each tab, I have a few controls. When I tried to implement the onClick method for my buttons, I found the buttons not responding to hand gestures, more specifically, the clicks.
Here is the class for the tab:
package com.telkitty.myPetProject
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.provider.Contacts;
import android.provider.ContactsContract;
public class ContactPage extends Fragment {
private static final int CONTACT_PICKER_RESULT = 1001;
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Activity activity = getActivity();
if (activity != null)
{
addListenerOnButton();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.contact_page, container, false);
return view;
}
public void onListItemClick(ListView l, View v, int position, long id) {
Activity activity = getActivity();
}
public void addListenerOnButton()
{
Button add = (Button) getView().findViewById(R.id.add_button);
add.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}});
}
}
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/edit_button"
android:layout_width="80dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_marginRight="10dp"
android:text="#string/edit_contact"/>
<Button
android:id="#+id/add_button"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="#string/add_contact"/>
<ListView
android:id="#+id/contact_list"
android:layout_width="320dp"
android:layout_height="380dp"
android:paddingTop="50dp" >
</ListView>
</RelativeLayout>
What have I done wrong?
Define your views in the onCreateView(..) of your Fragment and register the listeners as followed:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.contact_page, container, false);
Button lEditButton = (Button) view.findViewById(R.id.edit_button);
Button lAddButton = (Button) view.findViewById(R.id.add_button);
ListView lContactList = (ListView) view.findViewById(R.id.contact_list);
lEditButton.setOnClickListener(this);
lAddButton.setOnClickListener(this);
lContactList.setOnItemClickListener(this);
return view;
}
Implement the onClickListener and onItemClickListener interface:
public class ContactPage extends Fragment implements onClickListener, onItemClickListener {
By using these interfaces you will be forced to override the onClick(View v) and onItemClick(..) where you can handle your actions for the buttons and list.
Ok, it just happens my buttons were actually beneath the ListView, so although they looked as if they were there, everytime I clicked on them, the ListView was actually selected.
I added the marked line, now the button is working as it should.
public void addListenerOnButton()
{
Button add = (Button) getView().findViewById(R.id.add_button);
add.bringToFront(); // <--- this line
add.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}});
}