I'm making a chat activity for a school project and I want the newest messages at the bottom of the listView. Adding the code below does not work. I simply want the newest message to appear at the bottom and make the listView automatically scroll to the last list item. Thanks in advance!
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true"
Link to image of current situation
XML:
<android.support.v7.widget.Toolbar
android:id="#+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1a1a1a"
android:id="#+id/relativeLayout_Messages"
android:layout_below="#id/my_toolbar"
android:layout_alignBottom="#+id/imageView_Separator">
<ListView
android:id="#+id/listView_Messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stackFromBottom="true"
/>
</RelativeLayout>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView_Separator"
android:background="#1a1a1a"
android:src="#drawable/seperator"
android:layout_above="#+id/relativeLayout_ChatInput"
/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="#+id/relativeLayout_ChatInput"
android:background="#1a1a1a">
<EditText
android:layout_width="wrap_content"
android:layout_height="50dp"
android:id="#+id/editText_ChatInput"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="5dp"
android:background="#drawable/search_field"
android:layout_toStartOf="#+id/imageButton_Send"
android:layout_alignBottom="#+id/imageButton_Send"
android:inputType="textPersonName"
android:hint="#string/chat_field_hint"
android:textColor="#f4f5f6"
android:textColorHint="#f4f5f6"/>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/imageButton_Send"
android:background="#android:color/transparent"
android:src="#drawable/send_button"
android:scaleType="fitCenter"
android:layout_marginTop="10dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="6dp"
android:layout_marginBottom="8dp"
android:layout_alignParentEnd="true"
android:onClick="sendButtonClicked"
/>
</RelativeLayout>
</RelativeLayout>
JAVA
package com.example.muhryn.resonatem;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import java.util.*;
public class ChatActivity extends AppCompatActivity{
public void hideKeyboard() {
try {
InputMethodManager imm=(InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
} catch (Exception ex) { }
}
private ListView chatListView;
private Button submitButton;
private EditText chatEditText;
private Chat chat;
private ArrayList receivedList=new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
chatListView=(ListView)findViewById(R.id.listView_Messages);
chatEditText=(EditText)findViewById(R.id.editText_ChatInput);
chat=new Chat("A","Resonate");
chat.setListener(new Chat.Listener(){
public void received(final String received) {
System.out.println("Received: "+received);
runOnUiThread(new Runnable() {
public void run() {
hideKeyboard();
receivedList.add(0, received);
chatListView.setAdapter(new ChatList(ChatActivity.this, receivedList));
}
});
//////((ArrayAdapter)chatListView.getAdapter()).insert(received,0);
}
});
}
public void sendButtonClicked(View view){
String textToSubmit=chatEditText.getText().toString().trim();
if(textToSubmit.isEmpty())
return;
if(chat.submitted(textToSubmit)) {
receivedList.add(0,"Sent: "+textToSubmit);
chatListView.setAdapter(new ChatList(ChatActivity.this, receivedList));
} else
Toast.makeText(this,"Failed to submit "+textToSubmit+".",Toast.LENGTH_SHORT).show();
}
#Override
public void onStop () {
super.onStop();
chat.stop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chat_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.view_profile:
finish();
return true;
case R.id.report_match:
finish();
return true;
case R.id.add_match:
finish();
return true;
case R.id.unmatch:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Try the below code.
chatListView.smoothScrollByOffset(receivedList.size()-1);
It will scroll down to latest chat.
Related
my code works well, with 2 buttons ("home" and "chiudi") at the bottom, but I wanted to add more code to my webview app, and this new code hides my buttons.
This is the new code I want to add:
...
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView wView, String url)
{
if (url.startsWith("mailto:") || url.startsWith("tel:") || url.startsWith("geo:") ||
url.startsWith("http:") || url.startsWith("https:")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(intent);
return true;
} else if (url.startsWith("whatsapp:")) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
sendIntent.setPackage("com.whatsapp");
startActivity(sendIntent);
return true;
} else if (url.startsWith("spotify:")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
"spotify:album:0sNOF9WDwhWunNAHPD3Baj"));
intent.putExtra(Intent.EXTRA_REFERRER,
Uri.parse("android-app://" + context.getPackageName()));
startActivity(intent);
return true;
}
return false;
}
});
...
And this is my code:
for activity.main.xml:
...
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<Button
android:id="#+id/button"
android:layout_width="183dp"
android:layout_height="41dp"
android:layout_marginStart="191dp"
android:layout_marginLeft="171dp"
android:layout_x="207dp"
android:layout_y="629dp"
android:background="#0000ff"
android:onClick="clickexit"
android:text="Chiudi"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/swipe">
</Button>
<Button
android:id="#+id/button2"
android:layout_width="183dp"
android:layout_height="41dp"
android:layout_x="207dp"
android:layout_y="629dp"
android:background="#0000ff"
android:onClick="gohome"
android:text="Home"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button"
app:layout_constraintStart_toStartOf="parent">
</Button>
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="#0000ff"
android:textSize="40sp"
android:textAlignment="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
...
For MainActivity.java:
...
package it...........;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.onesignal.OneSignal;
public class MainActivity extends AppCompatActivity {
private static final String ONESIGNAL_APP_ID = "a..............";
private SwipeRefreshLayout swipeRefreshLayout;
private WebView webView;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textview);
textView.postDelayed(new Runnable() {
#Override
public void run() {
textView.setText("sto caricando");
}
}, 500); // delay of 2 seconds before setting a text to textView
textView.postDelayed(new Runnable() {
public void run() {
textView.setVisibility(View.GONE);
}
}, 2000);
// Enable verbose OneSignal logging to debug issues if needed.
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://d...app");
//per fare il refresh
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(false);
webView.reload();
}
}, 2000);
}
});
swipeRefreshLayout.setColorSchemeColors(
getResources().getColor(android.R.color.holo_blue_dark),
getResources().getColor(android.R.color.holo_orange_dark),
getResources().getColor(android.R.color.holo_green_dark),
getResources().getColor(android.R.color.holo_red_dark));
}
public void gohome(View v)
{
webView.loadUrl("https://...app");
}
public void clickexit(View v)
{
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else
super.onBackPressed();
}
}
...
When I add the first code, my buttons disappear.
How can I fix this?
Thank you
Roberto
Your alignment of views is not correct and In ConstraintLayout you have arranged your views by giving reference to other views. It would be good to check this link for a better understanding of how to use ConstraintLayout.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000ff"
android:onClick="gohome"
android:text="Home"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000ff"
android:onClick="clickexit"
android:text="Chiudi"
android:textColor="#color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#id/textview"
app:layout_constraintStart_toEndOf="#+id/button2" />
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text"
android:textAlignment="center"
android:textColor="#0000ff"
android:textSize="40sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am facing the problem of cannot see widgets in tab layouts. I have created textview and button in Overview Fragment but I cannot see them when run code. Is it right to initialize textviews and buttons in oncreateview() of fragment which we don't want to transfer to another tab. I have searched a lot about my problem but cannot get any hint. Code is given below:
package com.example.progluattempt;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
public class GlucosePlotterTips extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glucose_plotter_tips);
TabLayout Tablayout1 = findViewById(R.id.Tablayout1);
TabItem OverviewTab = findViewById(R.id.Overviewtab);
TabItem HistoryTab = findViewById(R.id.Historytab);
TabItem TipsTab = findViewById(R.id.Tipstab);
ViewPager Viewpager1 = findViewById(R.id.viewpagery1);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), Tablayout1.getTabCount());
Viewpager1.setAdapter(pagerAdapter);
Tablayout1.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Viewpager1.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
//PgeAdapter
package com.example.progluattempt;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
private int numoftabs;
public PagerAdapter(FragmentManager fm, int numoftabs){
super(fm);
this.numoftabs = numoftabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch(position){
case 0:
return new OverviewFragment();
case 1:
return new HistoryFragment();
case 2:
return new TipsFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numoftabs;
}
}
//Main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
tools:context=".GlucosePlotterTips">
<com.google.android.material.tabs.TabLayout
android:id="#+id/Tablayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.004">
<com.google.android.material.tabs.TabItem
android:id="#+id/Overviewtab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overview" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Historytab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="History" />
<com.google.android.material.tabs.TabItem
android:id="#+id/Tipstab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tips" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpagery1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
//fragmentOverview
<FrameLayout 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"
tools:context=".OverviewFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="183dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewov2"
android:layout_width="match_parent"
android:layout_height="56dp"
android:text="#string/overview1"
android:textColor="#color/black"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textViewov3"
android:layout_width="match_parent"
android:layout_height="46dp"
android:text="TextView"
android:textColor="#color/black"
android:textSize="18sp" />
</LinearLayout>
<Button
android:id="#+id/buttonov2"
android:layout_width="277dp"
android:layout_height="93dp"
android:layout_gravity="center"
android:text="#string/planner"
android:textColor="#color/black"
android:textSize="24sp"
app:backgroundTint="#color/Yellow" />
//OverviewFragment
package com.example.progluattempt;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class OverviewFragment extends Fragment {
TextView Results, Condition;
Button Mybuttonov2;
public OverviewFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_overview, container, false);
Results = (TextView) view.findViewById(R.id.textViewov2);
Intent i =getActivity().getIntent();
String LatestReading=i.getStringExtra("TimeofReading");
Results.setText("Last Checked: " +LatestReading);
//type
Condition = (TextView) view.findViewById(R.id.textViewov3);
String TypeofDiab = i.getStringExtra("Concentration");
Condition.setText("" +TypeofDiab);
//Button
Mybuttonov2 = (Button) view.findViewById(R.id.buttonov2);
//to display conditon of user
if(Condition.getText() != null){
String num;
int numi=0;
num = Condition.getText().toString();
try{
numi = Integer.parseInt(num);
}catch(NumberFormatException ex){
}
if(numi <= 70){
System.out.println("Hypoglycemia");}
else if(numi >=70 & numi <= 140){
System.out.println("Fine");}
else if(numi>140 & numi <200){
System.out.println("Prediabetes");}
else {
System.out.println("Hyperglycemia");
}
}
//to add click event for button
Mybuttonov2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i3 = new Intent(getActivity(), SensorScreen.class );
startActivity(i3);
}
});
return view;
}
}
Logcat
When run emulator
I have created the standard gesture detector that changes a textview depending on the given gesture. All works fine when my XML contains only the relative layout and the text view I wish to change. However when I add a gird layout and a few icons the Gesture Detector no longer works, simply not changing the textview as it did before.
The code is;
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:id="#+id/Relative_Layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#drawable/homebackground"
tools:context="com.example.james.fitness.MainActivity"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">
<GridLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/Grid1">
<TextView
android:id="#+id/someText"
android:text="sometext"
android:foregroundGravity="center_vertical|center_horizontal"
android:gravity="center_vertical|center"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleX="5"
android:scaleY="5"
android:textColor="#color/colorAccent" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="#drawable/fitnessbutton"
android:id="#+id/fitnessbutton"
android:layout_row="1"
android:layout_column="1"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:gravity="center"
android:paddingBottom="100dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="#drawable/drinkbutton"
android:id="#+id/drinkbutton"
android:layout_column="2"
android:layout_row="1"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:gravity="center"
android:paddingBottom="100dp" />
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="#drawable/foodbutton"
android:id="#+id/foodbutton"
android:layout_column="3"
android:layout_row="1"
android:layout_columnWeight="1"
android:layout_gravity="fill_horizontal"
android:gravity="center"
android:paddingBottom="100dp" />
</GridLayout>
</RelativeLayout>
And the Java
import android.app.Activity;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements
GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {
private TextView someText;
private GestureDetectorCompat gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
someText = (TextView)findViewById(R.id.someText);
this.gestureDetector = new GestureDetectorCompat(this, this);
gestureDetector.setOnDoubleTapListener(this);
}
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
someText.setText("SINGLETAP");
return true;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
someText.setText("DOUBLETAP");
return true;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
someText.setText("DOUBLETAPEVENT");
return true;
}
#Override
public boolean onDown(MotionEvent e) {
someText.setText("DOWN");
return true;
}
#Override
public void onShowPress(MotionEvent e) {
someText.setText("PRESS");
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
someText.setText("SINGLETAPUP");
return true;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
someText.setText("SCROLL");
return true;
}
#Override
public void onLongPress(MotionEvent e) {
someText.setText("LONGPRESS");
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
someText.setText("FLING");
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return false;
}
}
Note if I comment out the grid layout and the image views then the code works again changing the textview. I can only presume the gesture detector is now buried beneath the grid layout but aren't sure?
Try to remove this lines in your layout, they are useless in your case
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
My Android listview does not update with notifydatasetchanged() call.
The Main Code Activity:
package com.example.jokesbook;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.jokesbook.MESSAGE";
CustomAdapter Adapter;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JokeDB.jokesList = new ArrayList<Joke>();
JokeDB.jokesList.add(new Joke("DDD"));
lv = (ListView)findViewById(android.R.id.list);
Adapter= new CustomAdapter(MainActivity.this, R.layout.joke_list_item, JokeDB.jokesList);
lv.setAdapter(Adapter);
}//onCreate
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Log.d("jokesbook", "onResume ");
Adapter.notifyDataSetChanged();
}
class CustomAdapter extends ArrayAdapter<Joke>{
Context context;
int layoutResourceId;
ArrayList<Joke> data = null;
private LayoutInflater mInflater;
public CustomAdapter(Context customAdapter, int layoutResourceId, ArrayList<Joke> data) {
super(customAdapter, layoutResourceId, data);
Log.d("jokesbook", "CustomAdapter ");
this.layoutResourceId = layoutResourceId;
this.context = customAdapter;
this.data = data;
this.mInflater = LayoutInflater.from(customAdapter);
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
//item_list
convertView = mInflater.inflate(R.layout.joke_list_item, null);
holder = new ViewHolder();
//fill the views
holder.joke = (TextView) convertView.findViewById(R.id.ListTextView1);
convertView.setTag(holder);
}
else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();//
}
holder.joke.setText(data.get(position).jokeStr);
return convertView;
}
class ViewHolder {
TextView joke;
}
}
/** Called when the user clicks the Add a new joke button */
public void goNewJoke(View view) {
Intent intent = new Intent(this, New_joke.class);
startActivity(intent);
}
}
Its 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/ButtonAboveList"
android:layout_width="500dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:onClick="goNewJoke"
android:text="#string/Add_a_new_joke"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
When adding content to JokeDB.jokesList in another activity that its code is:
package com.example.jokesbook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class New_joke extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_joke);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_joke, menu);
return true;
}
public void addJoke(View view){
EditText editTextJoke= (EditText)findViewById(R.id.edit_text_jokeToAdd);
JokeDB.jokesList.add(new Joke(editTextJoke.getText().toString()));
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
and its XML is:
<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:background="#color/green"
android:orientation="vertical"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="3dp"
tools:context=".New_joke" >
<EditText
android:id="#+id/edit_text_jokeToAdd"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginBottom="40dp"
android:background="#color/white"
android:hint="#string/edit_message" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
tools:context=".New_joke" >
<TextView
android:id="#+id/AuthorText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/Author"
android:textColor="#android:color/white"
android:textSize="25sp" />
<EditText
android:id="#+id/edit_text_Author"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#color/white"
android:hint="#string/Only_letters_allowed"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="60dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
tools:context=".New_joke" >
<TextView
android:id="#+id/DateText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/Date"
android:textColor="#android:color/white"
android:textSize="25sp" />
<EditText
android:id="#+id/edit_text_Date"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#color/white"
android:hint="#string/Only_digits_allowed"
android:inputType="number" />
</LinearLayout>
<Button
android:id="#+id/ButtonAboveList"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addJoke"
android:text="#string/Add" />
</LinearLayout>
I cannot see the updated list in the main activity eveb though in onResume I used notifydatasetchanged() function.
Try This....
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Log.d("jokesbook", "onResume ");
notifyDataSetChanged();
}
O.K i have looked around this site and others and i see something similar to what i am wanting but yet it isn't what i am wanting...let me explain
i am learning to build an android app using eclipse that has a media player linked to my shoutcast server i am running, so far the apps works great but it doesn't have an icon on the top were the notification area is and when i go to a different app (a game) to play while leaving the music playing it minimizes the app .. thats fine but when i reopen the app it doesnt stop the mediaplayer infact if i play the player i will have 2 players running i will then have to force stop it using the task manager,, i know this can be done as i have apps on my phone that has icons and it will do what i am wanting
when i searched this site i found a link to youtube that has soemthing similar to what i am wanting
http://www.youtube.com/watch?v=e74z0_Z5QWI&feature=relmfu the code that is shown is as followed
import android.app.Activity;
public class StatusBar extends Activity implements OnclickListener{
NotificationManager nm;
#Override
Protected void onCreate(bundle savedInstance){
//TODO Auto-generated method Stub
super.oncreate(savedInstaceState);
setContentView(R.layout.statusbar);
Button stat = (Button)findViewById(R.id.bStatusBar);
stat.setOnClickListener(this);
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public void onClick(View v){
//TODO Auto-generated method Stub
Intent intent = new Intent(this, StatusBar.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
}
i have add this code to my MainActivity.java but it spits several errors to me that i have tried to fix using quickfix here is the script i currently have in my MainActivity.java file
package com.myapp.mytapp;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://link to url:8002";
private final Handler handler = new Handler();
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(true);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(true);
seekBar = (SeekBar)findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar)v;
mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
//Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
}
private void playAudio() {
mediaPlayer.start();
btn_play.setEnabled(true);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
public void homepage (View view) {
goToUrl ( "http://myhomepage.com/");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
}
here is what is in my activity_main.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"
android:background="#color/black"
android:icon="#drawable/ic_launcher"
android:orientation="vertical"
startForeground()>
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/logo" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/homepage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="web"
android:clickable="true"
android:cursorVisible="true"
android:linksClickable="true"
android:onClick="homepage"
android:text="Home Page" />
</TableRow>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_play"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/play"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/play" >
</Button>
<Button
android:id="#+id/btn_pause"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/pause"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/pause" >
</Button>
<Button
android:id="#+id/btn_stop"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:background="#drawable/stop"
android:clickable="true"
android:cursorVisible="true"
android:src="#drawable/stop" >
</Button>
</LinearLayout>
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" >
</SeekBar>
<ImageView
android:id="#+id/imageView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/scast" />
<TextView
android:id="#+id/Textview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:hint="#string/version" >
</TextView>
</LinearLayout>
can someone tell me what i did wrong or can rewrite what i have and still keep everything working
Thanks in advance
Rob